package com.genius.smsservice.coursemanage.service.impl;

import com.genius.smsbase.Domain.Result;
import com.genius.smsbase.Service.impl.GenericManagerImpl;
import com.genius.smsbase.util.ResultUtil;
import com.genius.smsdao.coursemanage.dao.CourseDao;
import com.genius.smsdao.coursemanage.domain.Course;
import com.genius.smsdao.studentmanage.dao.StudentDao;
import com.genius.smsdao.studentmanage.domain.Student;
import com.genius.smsservice.coursemanage.service.CourseManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


/**
 * @ClassName CourseManagerImpl
 * @Description CourseManager实现类
 * @author：gpf
 */
@Component
public class CourseManagerImpl extends GenericManagerImpl<Course,Long> implements CourseManager {

    CourseDao courseDao;
    @Resource
    StudentDao studentDao;

    @Autowired
    public void setCourseDao(CourseDao courseDao) {
        this.courseDao = courseDao;
        this.dao = this.courseDao;
    }


    @Override
    public Result add_student(String studentnum, String coursename){
        System.out.println("学生学号"+studentnum+"课程名字"+coursename);
        Course course = courseDao.findByName(coursename);
        if(!studentDao.findByNumber(studentnum).isPresent()){
            return ResultUtil.error("添加失败,该学生不存在");
        }
        if(Objects.isNull(courseDao.findByName(coursename))){
            return ResultUtil.error("添加失败,该课程不存在");
        }
        Student student = studentDao.findByNumber(studentnum).get();
        List<Student> studentList = course.getStudentList();
        if(Objects.isNull(studentList)){
            studentList = new ArrayList<Student>();
        }
        if(studentList.contains(student)){
            return ResultUtil.error("添加失败,您已经选过该课程");
        }else{
            studentList.add(student);
            course.setStudentList(studentList);
            courseDao.save(course);
            return ResultUtil.success("添加成功");
        }
    }

    @Override
    public Result del_student(String studentnum, String coursename){
        Course course = courseDao.findByName(coursename);
        List<Student> studentList = course.getStudentList();
        Student student = studentDao.findByNumber(studentnum).get();
            studentList.remove(student);
            course.setStudentList(studentList);
            courseDao.save(course);
            return ResultUtil.success("删除成功");
    }




}
